/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.SLC;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import merlion.crm.slcm.entity.OrderDiscountGroup;
import merlion.crm.slcm.session.SLCSessionBeanLocal;
import merlion.mrp.ppm.entity.Product;

/**
 *
 * @author Kenn
 */
@ManagedBean(name = "odgManagerBean")
@ViewScoped
public class OrderDiscountManagerBean {

    @EJB
    private SLCSessionBeanLocal slcSessionBean;
    private OrderDiscountGroup odg;
    private Product product;
    private List<OrderDiscountGroup> odgs;
    private Collection<Product> products;
    private Boolean create;
    public static final String orderDiscountGroup = "mdg";
    public static final String p = "product";
    public static final String booleanCreate = "create";

    //--------------------------------------------------------------------------
    //                              Constructor
    //--------------------------------------------------------------------------
    public OrderDiscountManagerBean() {
        System.out.println("OrDiscountManagerBean constructor");
        resetSession();
    }

    private void resetSession() {
        odg = new OrderDiscountGroup();
        product = new Product();
        odgs = new ArrayList<OrderDiscountGroup>();
        products = new ArrayList<Product>();
        create = true;
    }

    //--------------------------------------------------------------------------
    //                           Getter and Setter
    //--------------------------------------------------------------------------
    public OrderDiscountGroup getOdg() {
        OrderDiscountGroup value = (OrderDiscountGroup) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(orderDiscountGroup);
        if (value != null) {
            odg = value;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(orderDiscountGroup);
        } 
        return odg;
    }

    public void setOdg(OrderDiscountGroup odg) {
        this.odg = odg;
    }

    public List<OrderDiscountGroup> getOdgs() {
        return odgs;
    }

    public void setOdgs(List<OrderDiscountGroup> odgs) {
        this.odgs = odgs;
    }

    public Collection<Product> getProducts() {
        return products;
    }

    public void setProducts(Collection<Product> products) {
        this.products = products;
    }

    public Product getProduct() {
        Product value = (Product) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(p);
        if (value != null) {
            product = value;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(p);
        } 
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public Boolean getCreate() {
        Boolean value = (Boolean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(booleanCreate);
        if (value != null) {
            create = value;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(booleanCreate);
        }
        return create;
    }

    public void setCreate(Boolean create) {
        this.create = create;
    }

    //--------------------------------------------------------------------------
    //                      Manager Bean
    //--------------------------------------------------------------------------
    public String viewAllOrderDisocuntGroup() {
        return "viewAllOrderDiscountGroup?faces-redirect=true";
    }

    public List<OrderDiscountGroup> viewAllOrderDiscount() {
        //Set
        setOdgs(slcSessionBean.getAllOrderDiscountGroup());
        return odgs;
    }

    public String createOrderDiscountGroup(Long i) {

        if (i == 0) {
            //Reset Session
            resetSession();
            return "manageOrderDiscountGroup?faces-redirect=true";
        } else {
            // Validate
            if (!validate(odg, product)) {
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(orderDiscountGroup, odg);
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(p, product);
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(booleanCreate, create);
                return "manageOrderDiscountGroup";
            }
            System.out.println("Create: " + create);
            // Get Product
            product = slcSessionBean.getProductById(product.getId());
            odg.setProduct(product);

            if (getCreate()) {
                System.out.println("PERSIST");
                odg = slcSessionBean.createOrderDiscountGroup(odg);
                 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Order Discount Group", "successfully created."));
            } // If update, EJB to merge
            else {
                System.out.println("MERGE");
                odg = slcSessionBean.updateOrderDiscountGroup(odg);
                 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Member Discount Group", "successfully updated."));
            }

            // Reset Manager Bean odg and product object after creating
            resetSession();
            //Stay on the same page
            return "manageOrderDiscountGroup";
        }
    }

    public Collection<Product> getAllProduct() {

        setProducts(slcSessionBean.getAllProduct());

        return products;
    }

    public String updateOrderDiscountGroup(Long id) {
        try {
            setOdg(slcSessionBean.getOrderDiscountGroupById(id));
            setProduct(getOdg().getProduct());
            setCreate(false);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(orderDiscountGroup,  odg);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(p,  product);
             FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(booleanCreate,  create);
            return "manageOrderDiscountGroup";
        } catch (Exception e) {
            return "error";
        }
    }
    
    // hold value for deletion
    public void beforeDelete (Long id) {
        odg = slcSessionBean.getOrderDiscountGroupById(id);
    }
    
    public String deleteOrderDiscountGroup() {
        System.out.print("############################"+odg.getId());
        try{
            slcSessionBean.deleteOrderDiscountGroup(odg.getId());
            //odg = new OrderDiscountGroup ();
        }
        catch (Exception e) {
            System.out.print(e.getMessage());
            return "error";
        }
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Order Discount Group", "successfully deleted."));
        return "manageOrderDiscountGroup";
    }

    //-------------------------------------------------------------------------
    //              OrderDiscountManager Bean Customer Validator
    //-------------------------------------------------------------------------
    private boolean isAlphabetic(String str) {
        if (str.matches("[a-zA-Z\\s]*")) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isAlphanumeric(String str) {

        if (str.matches("[a-zA-z0-9\\s]*")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean isNumeric(String str) {
        if (str.matches("[0-9]*")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean isNotEmpty(String str) {
        if (str == null) {
            return false;
        }
        if (str.equals("")) {
            return false;
        }
        return true;
    }

    private boolean validate(OrderDiscountGroup odg, Product pd) {
        System.out.print("########################product passed to validate" + pd.getId());

        boolean valid = true;
        /*
        // Order Discount Group Name: Required, Alphanumeric
        if (!isNotEmpty(odg.getOrderDiscountGroup())) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Order Discount Group Name", "cannot be empty."));
        valid = false;
        }
        if (!isAlphanumeric(odg.getOrderDiscountGroup())) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Order Discount Group Name", "can only contain alphanumeric characters."));
        valid = false;
        }*/

        //Product: required 
        if (pd.getId() == (long) -1) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Product", "cannot be empty."));
            valid = false;
        }

        //Quantity: required, not 0
        if (odg.getQuantity() == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Quantity", "cannot be empty."));
            valid = false;
        } else {
            if (odg.getQuantity() <= 0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Quantity", "cannot be <= 0."));
                valid = false;
            }
        }

        //Order Discount: Required, not 0
        if (odg.getOrderDiscount() == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Order Discount", "cannot be empty."));
            valid = false;
        } else {
            if (odg.getOrderDiscount() <= 0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Order Discount", "cannot be <= 0."));
                valid = false;
            }
            if (odg.getOrderDiscount() >= 1) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Order Discount", "cannot be >= 1."));
                valid = false;
            }
        }

       

        if (getCreate()&&exist(odg)) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Order Discount Group", "already exists."));
            valid = false;
        }

        return valid;
    }

    private boolean exist(OrderDiscountGroup odg) {
        if(product.getId() == (long) -1)
            return false;
        System.out.print("#########################"+product.getId());
        product = slcSessionBean.getProductById(product.getId());
        odg.setProduct(product);
        setOdgs(slcSessionBean.getAllOrderDiscountGroup());
        boolean exist = false;
        setOdgs(slcSessionBean.getAllOrderDiscountGroup());
        for(int i = 0;i<odgs.size();i++){
            //System.out.print("#########################"+odgs.get(i).getProduct().getId());
            //System.out.print("#########################"+odg.getProduct().getId());
            //System.out.print("#########################"+odgs.get(i).getQuantity());
            //System.out.print("#########################"+odg.getQuantity());
            if(odgs.get(i).getProduct().getId()==odg.getProduct().getId()&&odgs.get(i).getQuantity()==odg.getQuantity()) {
                exist = true;
                return exist;
            }
        }
        return exist;


    }
    
    public SelectItem[] createFilterOptions()  {
         List<Product> temp = new ArrayList<Product>();
         temp = slcSessionBean.getAllProduct();
         SelectItem[] options = new SelectItem[temp.size() + 1]; 
 
         options[0] = new SelectItem("", "Select"); 
         //System.out.print(options[0]);
         //System.out.print(products.size());
         for(int i = 0; i < temp.size(); i++) {  
             options[i + 1] = new SelectItem(temp.get(i).getProductType(), temp.get(i).getProductType()); 
             //System.out.print(options[i+1]);
         }  
         
         return options;  
     }
}
